package event;
import java.awt.*;
import java.util.List;

import user_source.TankClient;

/**
 * 
 * @author 
 *
 */
public class Missile {
	public static final int X_SPEED = 10;
	public static final int Y_SPEED = 10;
	
	public static final int WIDTH = 10;
	public static final int HEIGHT = 10;
	
	private static int ID = 1;
	
	private TankClient tc;
	public int tankId;
	public int id;
	
	public int x;
	public int y;
	public Direction dir = Direction.R;
	public boolean live = true;
	public boolean good;


	public Missile(int tankId,int x, int y,boolean good, Direction dir) {
		this.tankId = tankId;
		this.x = x;
		this.y = y;
		this.good = good;
		this.dir = dir;
		this.id = ID++;
	}

	public Missile(int tankId,int x,int y,boolean good,Direction dir,TankClient tc) {
		this(tankId,x,y,good,dir);
		this.tc = tc ;
	}
	
	public void draw(Graphics g) {
		if(!live) {
			//如果炮弹击中坦克，则不再画出这枚炮弹
			tc.missiles.remove(this);
			return;
		}
		
		Color c = g.getColor();
		g.setColor(Color.BLACK);
		g.fillOval(x,y,WIDTH,HEIGHT);
		g.setColor(c);
		
		move();
	}
	
	/**
	 * 实现炮弹行走的方法
	 */
	void move() {
		
		
		switch(dir) {
		case L:
			x -= X_SPEED;
			break;
		case LU:
			x -= X_SPEED/1.414;
			y -= Y_SPEED/1.414;
			break;
		case U:
			y -= Y_SPEED;
			break;
		case RU:
			x += X_SPEED/1.414;
			y -= Y_SPEED/1.414;
			break;
		case R:
			x += X_SPEED;
			break;
		case RD:
			x += X_SPEED/1.414;
			y += Y_SPEED/1.414;
			break;
		case D:
			y += Y_SPEED;
			break;
		case LD:
			x -= X_SPEED/1.414;
			y += Y_SPEED/1.414;
			break;
			default:
		}
		
		//判断导弹是否出界,出界就把这枚导弹删除
		if(x < 0 || y < 0 || x > TankClient.GAMME_WIDTH || y > TankClient.GAMME_HEIGHT) {
			live = false;
		}
	}
	
	public Rectangle getRect() {
		return new Rectangle(x,y,WIDTH,HEIGHT);
	}
	
	/**
	 * 导弹的攻击方法
	 * @param t
	 * @return
	 */
	public boolean hitTank(Tank t) {
		//判断坦克和炮弹是否重合，坦克是否存在
		if(this.live && t.isLive() && this.good != t.good &&this.getRect().intersects(t.getRect())) {
			t.setLive(false);
			this.live = false;
			//在导弹击中坦克的地方产生爆炸
			Explode e = new Explode(x,y,tc);
			//将一个爆炸加入列表
			tc.explodes.add(e);
			return true;
		}
		return false;
	}
	
	public boolean hitTanks(List<Tank> tanks) {
		for(int i=0; i<tanks.size(); i++) {
			if(this.hitTank(tanks.get(i))) {
				return true;
			}
		}
		return false;
	}
	
	public boolean isLive() {
		return live;
	}

	public void setLive(boolean live) {
		this.live = live;
	}
	
}
